/** $dialog 获取当前弹框 */
import { findComponentsDownward } from '@admin/utils/index';

let currentDialog = null;
let appInstance = null;

export default {
  // 设置当前应用实例
  setAppInstance(app) {
    appInstance = app;
  },

  // 设置cd
  setCurrentDialog() {
    if (!appInstance) {
      // 尝试从全局获取应用实例
      const appElement = document.querySelector('#app');
      if (appElement && appElement._instance) {
        appInstance = appElement._instance;
      } else {
        console.warn('无法获取 Vue 应用实例');
        return;
      }
    }

    const dialogVms = findComponentsDownward(appInstance, 'ElDialog') || [];
    if (dialogVms.length) {
      const topDialog = Array.from(dialogVms).sort((a, b) => {
        return Number(b.$el.style.zIndex) - Number(a.$el.style.zIndex);
      });
      currentDialog = topDialog[0];
    } else {
      currentDialog = null;
    }
  },
  close() {
    if (currentDialog && currentDialog.handleClose) {
      currentDialog.handleClose();
    }
  }
};
